import axios from "axios";
import qs from "querystring";
import { checkTUrl } from "../../utils/auth";
let proList = []; // 暂存产品合约信息列表
let parList = []; // 暂存货币汇率列表
let leadList = []; // 暂存排行榜数据
let recList = []; // 暂存跟单记录数据

const state = {
  miniLoading: false, // 迷你交易面板loading
  moneylist: [], // 当前币种列表
  contractlist: [], // 合约代码信息列表（主页table使用）
  actcontract: null, // （列表页）选中的合约id
  productlist: [], // 产品合约代码信息列表（20; 交易面板使用）
  latestMarket: [], // 最新行情信息
  paritiesList: [], // 货币汇率列表
  kbars: [], // K线数据
  getKEnd: 0, // K线数据 是否转换完成标记
  ActQuotes: {}, // 最新行情数据（K线页面使用）
  leaderboard: [], // 排行榜数据
  recordList: [], // 跟单记录列表
  diskType: "1", // 1为模拟盘0为实盘
  lastKLineData: [],
  floatPL: 0, //浮动盈亏
  pingYK: 0, //平仓盈亏
  history_bars: [],
};

const mutations = {
  SET_floatPL: (state, floatPL) => {
    // 存储当前浮动盈亏
    state.floatPL = floatPL * 1;
  },
  SET_pingYK: (state, pingYK) => {
    // 存储当前平仓盈亏
    state.pingYK = pingYK * 1;
  },
  // 迷你操作面板loading状态更改
  SET_MINILOADING: (state, isShow) => {
    state.miniLoading = isShow;
  },
  SET_MONEYLIST: (state, moneylist) => {
    // 存储当前币种列表数据
    state.moneylist = moneylist;
    //console.log('币种列表', moneylist)
  },
  SET_CONTRACTLIST: (state, cotemporary) => {
    // 存储合约代码信息列表
    state.contractlist = cotemporary;
  },
  SET_ACTCONTRACT: (state, contract) => {
    // 设置当前选中的合约行情数据
    state.actcontract = contract;
  },
  SET_DISKTYPE: (state, type) => {
    // 存储当前实盘模拟盘类别
    state.diskType = type;
  },
  SET_NEWMONEY: (state, mon) => {
    let {
      currencyId, //  货币ID
      accountBalance, // 账户余额
      frozenAmount, // 冻结金额
      floatPL, // 浮动盈亏
      riskFund, // 风险金
      overnightRF, // 隔夜风险金
      occupationMargin, // 占用保证金
    } = mon;

    for (let i = 0; i < state.moneylist.length; i++) {
      if (state.moneylist[i].currencyId == currencyId) {
        if (accountBalance != "a")
          state.moneylist[i].accountBalance = accountBalance;
        if (frozenAmount != "a") state.moneylist[i].frozenAmount = frozenAmount;
        if (floatPL != "a") state.moneylist[i].floatPL = floatPL;
        if (riskFund != "a") state.moneylist[i].riskFund = riskFund;
        if (overnightRF != "a") state.moneylist[i].overnightRF = overnightRF;
        if (occupationMargin != "a")
          state.moneylist[i].occupationMargin = occupationMargin;
        break;
      }
    }
    //console.log('moneyList', mon);

    //console.log('moneylist',state.moneylist)
  },
  SET_LOWCUR: (state, curlist) => {
    let {
      currencyId, //  货币ID
      lastReserve, // 上次结算准备金
      deposit, // 今日入金
      withdrawal, // 今日出金
      adjustment, // 今日调整
      transfer, // 今日划拨
      curConversion, // 今日货币转换
      liquidatePL, // 平仓盈亏
      handlingFee, // 手续费
      overnightRF, // 隔夜风险金
    } = curlist;
    for (let i = 0; i < state.moneylist.length; i++) {
      if (state.moneylist[i].currencyId == currencyId) {
        if (lastReserve !== "a") state.moneylist[i].lastReserve = lastReserve;
        if (deposit !== "a") state.moneylist[i].deposit = deposit;
        if (withdrawal !== "a") state.moneylist[i].withdrawal = withdrawal;
        if (adjustment !== "a") state.moneylist[i].adjustment = adjustment;
        if (transfer !== "a") state.moneylist[i].transfer = transfer;
        if (curConversion !== "a")
          state.moneylist[i].curConversion = curConversion;
        if (liquidatePL !== "a") state.moneylist[i].liquidatePL = liquidatePL;
        if (handlingFee !== "a") state.moneylist[i].handlingFee = handlingFee;
        if (overnightRF !== "a") state.moneylist[i].overnightRF = overnightRF;
        break;
      }
    }
  },
  SET_PRODUCTLIST: (state, list) => {
    state.productlist = list;
  },
  SET_LATESTMARKET: (state, list) => {
    state.latestMarket = list;
  },
  SET_PARITIESLIST: (state, list) => {
    state.paritiesList = list;
    // console.log('货币汇率：', state.paritiesList)
  },
  SET_BARS: (state, klist) => {
    state.length = 0;
    state.kbars = klist;
  },
  SET_LASTKLINEDATA: (state, klist) => {
    //console.log(klist)
    state.lastKLineData = klist;
  },
  SET_GETKDATAEnd: (state, status) => {
    state.getKEnd = status;
  },
  SET_ACTQUOTES: (state, hq) => {
    state.ActQuotes = hq;
  },
  SET_LEADERBOARD: (state, list) => {
    state.leaderboard = list;
    // console.log(state.leaderboard)
  },
  // 跟单列表
  SET_RECORDLIST: (state, rlist) => {
    state.recordList = rlist;
    // console.log(state.recordList)
  },
  SET_HISTORY_BARS: (state, data) => {
    state.history_bars = data;
  },
};

const actions = {
  updateMiniloading: ({ commit }, flag) => {
    commit("SET_MINILOADING", flag);
  },
  updateActcontract: ({ commit }, con) => {
    commit("SET_ACTCONTRACT", con);
  },
  getfloatPL: ({ commit }, list) => {
    commit("SET_floatPL", list);
  },
  getpingYK: ({ commit }, list) => {
    commit("SET_pingYK", list);
  },
  // 更新币种列表
  updateCurList: ({ commit }, list) => {
    let nowArr = list.map((v) => {
      return {
        currencyId: v.currencyId, //  货币ID
        accountBalance: v.accountBalance * 1, // 账户余额
        frozenAmount: v.frozenAmount * 1, // 冻结金额
        floatPL: v.floatPL * 1, // 浮动盈亏
        lastReserve: v.lastReserve * 1, // 上次结算准备金
        deposit: v.deposit * 1, // 今日入金
        withdrawal: v.withdrawal * 1, // 今日出金
        adjustment: v.adjustment * 1, // 今日调整
        transfer: v.transfer * 1, // 今日划拨
        curConversion: v.curConversion * 1, // 今日货币转换
        liquidatePL: v.liquidatePL, // 平仓盈亏
        handlingFee: v.handlingFee * 1, // 手续费
        deferredFee: v.deferredFee * 1, // 延期费
        riskFund: v.riskFund * 1, // 风险金
        overnightRF: v.overnightRF * 1, // 隔夜风险金
        occupationMargin: v.occupationMargin * 1, // 占用保证金
      };
    });
    commit("SET_MONEYLIST", nowArr);
  },
  // 更新详细资金列表
  updateLowCurList: ({ commit }, list) => {
    // 格式：5;币种ID;上次结算准备金;今日入金;今日出金;今日调整;今日划拨;今日货币转换;平仓盈亏;手续费;隔夜费;
    let [
      ,
      currencyId,
      lastReserve,
      deposit,
      withdrawal,
      adjustment,
      transfer,
      curConversion,
      liquidatePL,
      handlingFee,
      overnightRF,
    ] = list;
    let obj = {
      currencyId, //  货币ID
      lastReserve, // 上次结算准备金
      deposit, // 今日入金
      withdrawal, // 今日出金
      adjustment, // 今日调整
      transfer, // 今日划拨
      curConversion, // 今日货币转换
      liquidatePL, // 平仓盈亏
      handlingFee, // 手续费
      overnightRF, // 隔夜风险金
    };
    // console.log('币种列表更新：', obj)
    commit("SET_LOWCUR", obj);
  },
  // 更简要资金列表
  updateMoneyLIST: ({ commit }, list) => {
    let [
      ,
      currencyId, //  货币ID
      accountBalance, // 账户余额
      frozenAmount, // 冻结金额
      floatPL, // 浮动盈亏
      riskFund, // 风险金
      overnightRF, // 隔夜风险金
      occupationMargin, // 占用保证金
    ] = list;

    let obj = {
      currencyId, //  货币ID
      accountBalance, // 账户余额
      frozenAmount, // 冻结金额
      floatPL, // 浮动盈亏
      riskFund, // 风险金
      overnightRF, // 隔夜风险金
      occupationMargin, // 占用保证金
    };
    //console.log('币种列表更新：', list)

    commit("SET_NEWMONEY", obj);
  },
  // 更新合约品种信息列表 20
  updateProductList: ({ commit }, plist) => {
    if (plist[1] === "5") {
      proList = [];
      commit("SET_PRODUCTLIST", []);
      // console.log('总数：' + plist[2])
      return;
    }

    let [
      ,
      ,
      ContractID,
      ContractCode,
      Name,
      MarketName,
      Multiplier,
      OpenFee,
      CYFee,
      CTFee,
      Currency,
      Minimum,
      Unit,
      RiskGold,
      Overnight,
      ClientCur,
      OMargin,,
	  RMultiplier,
    ] = plist;

    if (ContractID === "0") {
      commit("SET_PRODUCTLIST", proList);
    } else {
      let obj = {
        ContractID, // 期货合约合约ID
        ContractCode, // 期货合约代号
        Name, // 名称
        MarketName, // 市场名称
        Multiplier: Multiplier * 1, // 客户端合约乘数
        OpenFee: OpenFee * 1, // 建仓手续费
        CYFee: CYFee * 1, // 平昨手续费
        CTFee: CTFee * 1, // 平今手续费
        Currency, // 币种
        Minimum: Minimum * 1, // 最小波动
        Unit, // 单位
        RiskGold: RiskGold * 1, // 风险金
        Overnight: Overnight * 1, // 隔夜权益金
        ClientCur, // 客户端显示币种
        OMargin: OMargin * 1, // 建仓保证金
		RMultiplier: RMultiplier * 1, // 真实合约乘数
      };

      proList.push(obj);
    }
  }, // 更新最新合约行情信息（交易面板享用）
  updateLatestMarket: ({ commit }, mlist) => {
    commit("SET_LATESTMARKET", mlist);
  },
  // 更新货币汇率
  updateParities: ({ commit }, plist) => {
    if (plist[1] === "5") {
      // console.log('总数为：' + plist[2])
      parList = [];
      commit("SET_PARITIESLIST", []);
      return;
    }

    let [, , ID, Name, Unit, Shorthand, Ratio, Poundage, Sign] = plist;

    if (ID === "0") {
      commit("SET_PARITIESLIST", parList);
    } else {
      let obj = {
        ID, // 货币ID
        Name, // 货币名称
        Unit, // 单位
        Shorthand, // 单位简写
        Ratio, // 货币比率
        Poundage, // 手续费
        Sign, // 主货币标志
      };

      parList.push(obj);
    }
  },
  historyKline: ({ commit, state }, data) => {
    if(!data){
      commit("SET_HISTORY_BARS", []);
    }
    if (data.indexOf(";") === -1) {
      let onceData = data.split(",");
      let nowObj = {
        close: onceData[5] * 1,
        high: onceData[3] * 1,
        low: onceData[4] * 1,
        open: onceData[2] * 1,
        time: onceData[1] * 1000,
        volume: onceData[6] * 1 < 0 ? 0 : onceData[6] * 1,
      };
      commit("SET_LASTKLINEDATA", nowObj); // 设置K线数据
      return;
    }
    let dataArr = data.split(";");
    dataArr = dataArr.filter((v) => v.length > 2);
    let newData = dataArr.map((V) => {
      let v = V.split(",");
      let nowObj = {
        close: v[5] * 1,
        high: v[3] * 1,
        low: v[4] * 1,
        open: v[2] * 1,
        time: v[1] * 1000,
        volume: v[6] * 1 < 0 ? 0 : v[6] * 1,
      };
      return nowObj;
    });
    newData = newData.sort(function(a, b) {
      return a.time - b.time;
    });
    commit("SET_HISTORY_BARS", newData); // 设置K线数据
  },
  // 更新 K线数据
  updateKLines: ({ commit, state }, data) => {
    if (data.indexOf(";") === -1) {
      let onceData = data.split(",");
      let nowObj = {
        close: onceData[5] * 1,
        high: onceData[3] * 1,
        low: onceData[4] * 1,
        open: onceData[2] * 1,
        time: onceData[1] * 1000,
        volume: onceData[6] * 1 < 0 ? 0 : onceData[6] * 1,
      };
      commit("SET_LASTKLINEDATA", nowObj); // 设置K线数据
      return;
    }
    let dataArr = data.split(";");
    dataArr = dataArr.filter((v) => v.length > 2);
    let newData = dataArr.map((V) => {
      let v = V.split(",");
      let nowObj = {
        close: v[5] * 1,
        high: v[3] * 1,
        low: v[4] * 1,
        open: v[2] * 1,
        time: v[1] * 1000,
        volume: v[6] * 1 < 0 ? 0 : v[6] * 1,
      };
      return nowObj;
    });
    newData = newData.sort(function(a, b) {
      return a.time - b.time;
    });
    commit("SET_BARS", newData); // 设置K线数据
  },
  // 更新当前选中的合约行情数据
  updateActQuotes: ({ commit }, nowhq) => {
    commit("SET_ACTQUOTES", nowhq);
  },
  // 更新排行榜数据
  updateLeaderboard: ({ commit }, nowList) => {
    // 26;1;排行榜类别;排行期间;币种;顺序;用户ID;用户名;盈亏;在线状态;
    let [
      ,
      ,
      Type,
      Period,
      Currency,
      Sequence,
      UserID,
      UserName,
      ProfitLoss,
      Status,
    ] = nowList;
    if (Type === "0") {
      commit("SET_LEADERBOARD", leadList);
      leadList = [];
    } else {
      if (UserName.startsWith("bd") || UserName.startsWith("BD")) {
        return;
      }
      let obj = {
        Type, // 排行榜类别
        Period, // 排行期间
        Currency, // 币种
        CurText:
          Currency === "1" ? "人民币" : Currency === "3" ? "美元" : "港币",
        Sequence, // 顺序
        UserID, // 用户ID
        UserName, // 用户名
        ProfitLoss, // 盈亏
        Status, // 在线状态l
      };

      leadList.push(obj);
    }
  },
  // 更新跟单列表
  updateDocumentary: ({ commit }, list) => {
    // 28;1;ID;用户ID;用户名;合约ID;操作类别;数量;跟单类别;超价倍数;数量类别;
    let [
      ,
      ,
      ID,
      UserID,
      UserName,
      ContractID,
      Type,
      Quantity,
      RecordType,
      Multiple,
      AmountType,
    ] = list;
    if (ID === "0") {
      commit("SET_RECORDLIST", recList);
      recList = [];
    } else {
      let obj = {
        ID, // ID
        UserID, // 用户ID
        UserName, // 用户名
        ContractID, // 合约ID
        Type, // 操作类别
        Quantity: Quantity * 1, // 数量
        RecordType, // 跟单类别
        Multiple: Multiple * 1, // 超价倍数
        AmountType, // 数量类别
      };

      recList.push(obj);
    }
  },
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
};
